package com.movisol.questionwizard.views;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextSwitcher;
import android.widget.Toast;

import com.movisol.adsservice.client.BannerViewer;
import com.movisol.questionwizard.activities.CustomActivity;
import com.movisol.questionwizard.interfaces.ScreenViewable;
import com.movisol.questionwizard.payment.SmsPayment;
import com.movisol.questionwizard.views.controls.SmsPopUp;
import com.movisol.questionwizard.views.listeners.MessageDeliveredEvent;
import com.movisol.questionwizard.views.listeners.MessageDeliveredListener;
import com.movisol.tools.HelperUtils;
import com.movisol.tools.constants.Constants;

public class MainPage extends CustomActivity implements OnClickListener, ScreenViewable, MessageDeliveredListener {
	private static final int REQUEST_SPLASH = 1;
	private static final int MAIN_BANNER_SLOT_ID = 11;
	private static final int MAIN_BANNER_SLOT_ID_AZ = 16;
	private static final int MAIN_BANNER_SLOT_ID_SS = 21;
	private Button btnStart;
	private TextSwitcher ts;
	
	private List<Profile> profileArray;
	private PopupWindow popupWindow = null;
	private SmsPopUp smsPopUp = null;
	private SmsPayment smsPayment = null;
	private int group;
	private String groupString;
	private int girlsActived = 0;

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);  
		ac.setExit(true);
		
		// Retrieves general information about the phone
		DisplayMetrics metrics = new DisplayMetrics();

		// Gets the metrics that give us the density information
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		ac.setDisplayMetrics(metrics);

		setContentView(HelperUtils.getLayoutResource("mainpage", getApplicationContext()));
		context = ac.getContext();

		if(profileArray == null)
			profileArray = new ArrayList<Profile>();
		
		group = HelperUtils.getRandomGroup(getApplicationContext());
		
		switch(group)
		{
			case HelperUtils.GROUP_A:
				Log.d("MainPage", "Group: A");
				groupString = "A";
				ac.setActivesGirls(HelperUtils.getGirlsNumber(getApplicationContext()));
				break;
			case HelperUtils.GROUP_B:
				Log.d("MainPage", "Group: B");
				groupString = "B";
				ac.setActivesGirls(1);
				break;
			case HelperUtils.GROUP_C:
				Log.d("MainPage", "Group: C");
				groupString = "C";
				ac.setActivesGirls(1);
				break;
		}
		
		/*
		 * Si no se han cargado los recursos en el aplication controller se
		 * llama a la vista splash para que los carge en background y cuando
		 * termine inicializa los controles,sino como ya estan cargados los
		 * recursos se inicializan controles
		 */
//		if (!ac.isLoaded()) {
			ac.setSplashing(true);
			Intent splashView = new Intent(this, Splash.class);
			startActivityForResult(splashView, REQUEST_SPLASH);
//		} else {
//			ac.setSplashing(false);
//			initializeControls();
//		}
	}	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_SPLASH)
		{
			ac.setSplashing(false);
			context = ac.getContext();
			initializeControls();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if(ac.isNeedAppToReboot() && !ac.isSplashing())
		{
			ac.setSplashing(true);
			ac.getUsageClient().stopTracking();
			Intent splashView = new Intent(this, Splash.class);
			startActivityForResult(splashView, REQUEST_SPLASH);
		}
		else
			if(ts != null && ac.getLiteralsValueByKey("helpWebBody") != null)
			{
				ts.setText(Html.fromHtml(ac.getLiteralsValueByKey("homeWebBody")));
				btnStart.setText(ac.getLiteralsValueByKey("start"));
				
			}
		int i = 1;
		for(Profile profile : profileArray)
		{
			if(HelperUtils.isGalleryEnabledForProfile(context, i))
				profile.enableMirameButton();
			i++;
		}
	}
	
	private class AsyncLoadRaw extends AsyncTask<Integer, Void, Integer[]>{

		@Override
		protected Integer[] doInBackground(Integer... params) {
			ac.setQuestionsResourcesId(HelperUtils.getRawResource("appconfig"+params[0], context));
			ac.readQuestions(params[0]-1);
			return params;
		}

		@Override
		protected void onPostExecute(Integer[] result) {
			super.onPostExecute(result);
			ac.setNeedAppToReboot(false);
			popupWindow.dismiss();
			profileArray.get(result[0]-1).getBtnSeduceme().setEnabled(true);
			
			if(result[1] == HelperUtils.TEST)
			{
				goToTest();
			}
		}
		
	}
	
	private void checkActiveProfileForIndex(Profile profile, int index)
	{
		Log.d("MainPage","Girl# "+index);
		if(HelperUtils.isGalleryEnabledForProfile(context, index))
			profile.enableMirameButton();
		if(HelperUtils.isTestEnabledForProfile(context, index))
			profile.enableSeducemeButton();
		
		if(ac.getActivesGirls() != null && ac.getActivesGirls() > girlsActived)
		{
			switch(group)
			{
				case HelperUtils.GROUP_A:
					if(!HelperUtils.isTestEnabledForProfile(context, index))
					{
						activeTestForIndex(profile, index);
						Log.d("MainPage","Enabliing test");
					}
					break;
				case HelperUtils.GROUP_B:
					if(!HelperUtils.isTestEnabledForProfile(context, index))
					{
						activeTestForIndex(profile, index);
						Log.d("MainPage","Enabliing test");
					}
					if(!HelperUtils.isGalleryEnabledForProfile(context, index))
					{
						activeGalleryForIndex(profile, index);
						Log.d("MainPage","Enabliing gallery");
					}
					break;
				case HelperUtils.GROUP_C:
					if(!HelperUtils.isTestEnabledForProfile(context, index))
					{
						activeTestForIndex(profile, index);
						Log.d("MainPage","Enabliing test");
					}
					break;
			}

			girlsActived++;
		}
		
	}

	private void activeTestForIndex(Profile profile, int index)
	{
		HelperUtils.setTestEnabledForProfile(context, index);
		profile.enableSeducemeButton();
	}
	
	private void activeGalleryForIndex(Profile profile, int index)
	{
		HelperUtils.setGalleryEnabledForProfile(context, index);
		profile.enableMirameButton();
	}

	public void initializeControls() {	

		RelativeLayout rLayout = (RelativeLayout) findViewById(HelperUtils.getIdResource("mainPageMainLayout", context));
		rLayout.setBackgroundResource(HelperUtils.getDrawableResource("backgroundhome", context));

		girlsActived = 0;
		
		
		
		switch(group)
		{
			case HelperUtils.GROUP_A:
				HelperUtils.setPayByQuestion(context, true);
				HelperUtils.setPayByGallery(context, true);
				HelperUtils.setActiveGalleryByFinishingTest(context, true);
				break;
			case HelperUtils.GROUP_B:
				HelperUtils.setPayByGirl(context, true);	
				break;
			case HelperUtils.GROUP_C:
				HelperUtils.setPayByTest(context, true);
				HelperUtils.setPayByGallery(context, true);
				break;
		}
		
		int girls = HelperUtils.getGirlsNumber(context);
		if(profileArray != null && profileArray.size() == 0)
			for(int i = 1; i < girls+1; i++)
			{
				Profile profile = (Profile) findViewById(HelperUtils.getIdResource("profile"+(i), context));
				if(profile != null)
				{
					profile.setNombre(ac.getLiteralsValueByKey("nameG"+i));
					profile.setEdad(ac.getLiteralsValueByKey("ageG"+i));
					profile.setPais(ac.getLiteralsValueByKey("countryG"+i));
					profile.getTvDescripcion().setText(Html.fromHtml(ac.getLiteralsValueByKey("descriptionG"+i)));
					profile.getTvInfo().setText(profile.getNombre()+" "+profile.getEdad()+" "+profile.getPais());
					profile.getIvFoto().setImageResource(HelperUtils.getDrawableResource("thumbnail"+i, context));
					
					profile.getBtnMirame().setOnClickListener(this);
					profile.getBtnSeduceme().setOnClickListener(this);
					
					checkActiveProfileForIndex(profile, i);
						
					profileArray.add(profile);
				}
			}


		// Initialize adBanner
		LinearLayout adLayout = (LinearLayout) findViewById(HelperUtils.getIdResource("mainPageAdLayout", context));
		adLayout.removeAllViews();
		if(ac.getSku().substring(ac.getSku().length()-2).equalsIgnoreCase("an"))
			bw = new BannerViewer(context, MAIN_BANNER_SLOT_ID,this);
		if(ac.getSku().substring(ac.getSku().length()-2).equalsIgnoreCase("az"))
			bw = new BannerViewer(context, MAIN_BANNER_SLOT_ID_AZ,this);
		if(ac.getSku().substring(ac.getSku().length()-2).equalsIgnoreCase("ss"))
			bw = new BannerViewer(context, MAIN_BANNER_SLOT_ID_SS,this);
		adLayout.addView(bw);

	}

	private void buttonPressedInViewForProfile(View v, int profileIndex)
	{
		if(v.getTag().equals("mirame"))
		{
			if(HelperUtils.isGalleryEnabledForProfile(context, profileIndex))
			{
				goToGallery();
			}
			else
			{
				if(HelperUtils.isPayByGirlnEnabled(context))
				{
					showSmsPopUp(ac.getLiteralsValueByKey("activeGirl"), groupString+"G"+profileIndex,profileIndex, HelperUtils.GALLERY);
				} else
				if(HelperUtils.isPayByGalleryEnabled(context))
				{
					//SHOW BUY GALLERY
					showSmsPopUp(ac.getLiteralsValueByKey("activeGallery"), groupString+"G"+profileIndex+"G",profileIndex, HelperUtils.GALLERY);
				}
				else
				{
					//MOSTRAR MENSAJE QUE EXPLIQUE COMO DESBLOQUEAR GALERIA
				}

			}
			
		} else
			if(v.getTag().equals("seduceme"))
			{
				if(HelperUtils.isTestEnabledForProfile(context, profileIndex))
				{
					goToTest();
				}
				else
				{
					if(HelperUtils.isPayByGirlnEnabled(context))
					{
						showSmsPopUp(ac.getLiteralsValueByKey("activeGirl"), groupString+"G"+profileIndex, profileIndex, HelperUtils.TEST);
					} else
					if(HelperUtils.isPayByTestyEnabled(context))
					{
						//SHOW BUY TEST
						showSmsPopUp(ac.getLiteralsValueByKey("activeTest"), groupString+"G"+profileIndex+"T",profileIndex, HelperUtils.TEST);
					}
					else
					{
						//MOSTRAR MENSAJE QUE EXPLIQUE COMO DESBLOQUEAR TEST
					}
				}
				
			}
		
	}
	
	private void goToGallery()
	{
		if(HelperUtils.checkConnectivity(context))
		{
			//GO TO GALLERY
			ac.setExit(false);
			Intent gallery = new Intent(this, Gallery.class);
			startActivity(gallery);
		}
		else
			HelperUtils.showToastMessage(context, Constants.NO_CONNECTIVITY_FOR_GALLERY, Toast.LENGTH_LONG);
	}
	
	private void goToTest()
	{
		//GO TO TEST
		ac.setExit(false);
		ac.start();
		Intent testView = new Intent(this, Test.class);
		startActivity(testView);
	}
	
	private void showSmsPopUp(final String popUpMessage, final String smsMessage, final int profileIndex, final int code)
	{
		smsPopUp = new SmsPopUp(context);
	
		popupWindow = new PopupWindow(this);	
		popupWindow.setContentView(smsPopUp);
		popupWindow.setOutsideTouchable(true);
		
		smsPayment = new SmsPayment(this, profileIndex, code);
		smsPayment.addMessageDeliveredListener(this);
	
		smsPopUp.changeToSmsPopUpWithMessage(popUpMessage); //message
		
		smsPopUp.getBtnOK().setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				smsPopUp.changeToWaitingPopupWithMessage(ac.getLiteralsValueByKey(Constants.WAITING_CONFIRMATION));
				smsPayment.sendSms(ac.getLiteralsValueByKey("smsNumber"), Constants.MOVISOL+smsMessage);
			}
		});
		
		smsPopUp.getBtnCancelar().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popupWindow.dismiss();
				
			}
		});
		
		
		RelativeLayout rLayout = (RelativeLayout) findViewById(HelperUtils.getIdResource("mainPageMainLayout", context));
		
		popupWindow.showAtLocation(rLayout,Gravity.CENTER, 0, 0);
		popupWindow.update(0,0,rLayout.getWidth(),rLayout.getHeight());
		popupWindow.getBackground().setAlpha(0);
		
	}
	
	@Override
	public void onClick(View v) {
		
		ViewParent parent = v.getParent();
		//Subo por los padres hasta encontrar la instancia de Profile
		while(!(parent instanceof Profile))
		{
			parent = parent.getParent();
		}
				
		int index = Integer.valueOf(((Profile)parent).getTag().toString());
		ac.setActiveProfileIndex(index);
		switch(index)
		{
		case 1:
			buttonPressedInViewForProfile(v,1);
			break;
		case 2:
			buttonPressedInViewForProfile(v,2);
			break;
		case 3:
			buttonPressedInViewForProfile(v,3);
			break;
		case 4:
			buttonPressedInViewForProfile(v,4);
			break;
		case 5:
			buttonPressedInViewForProfile(v,5);
			break;
		case 6:
			buttonPressedInViewForProfile(v,6);
			break;
		}		
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			
			if(popupWindow != null && popupWindow.isShowing())
				popupWindow.dismiss();
			else
			{
				ac.setExit(true);
				exit();
			}
			return true;
		}
		else
			return super.onKeyDown(keyCode, event);
	
	
	}

	@Override
	public void messageDelivered(MessageDeliveredEvent evt) {
		
		//Actualizar UI
		if(evt.getData().equals(SmsPayment.MESSAGE_DELIVERED))
		{
			for(Profile profile : profileArray)
			{
				if(Integer.valueOf(profile.getTag().toString()) == evt.getProfileIndex())
				{
					switch(evt.getCode())
					{
						case HelperUtils.GALLERY:
							HelperUtils.setGalleryEnabledForProfile(context, evt.getProfileIndex());
							profile.enableMirameButton();
							profile.getBtnMirame().setEnabled(true);
							profile.getBtnMirame().setText("Mirame");
							
							if(HelperUtils.isPayByGirlnEnabled(context))
							{
								HelperUtils.setTestEnabledForProfile(context, evt.getProfileIndex());
								profile.enableSeducemeButton();
								if(smsPopUp != null)
									smsPopUp.changeToWaitingPopupWithMessage(ac.getLiteralsValueByKey("loading"));
								new AsyncLoadRaw().execute(evt.getProfileIndex(), HelperUtils.GALLERY);
							}
					
							popupWindow.dismiss();
							goToGallery();

						break;
						case HelperUtils.TEST:
							
							if(HelperUtils.isPayByGirlnEnabled(context))
							{
								HelperUtils.setGalleryEnabledForProfile(context, evt.getProfileIndex());
								profile.enableMirameButton();
								profile.getBtnMirame().setEnabled(true);
								profile.getBtnMirame().setText("Mirame");
							}
							
							HelperUtils.setTestEnabledForProfile(context, evt.getProfileIndex());
							profile.enableSeducemeButton();
							if(smsPopUp != null)
								smsPopUp.changeToWaitingPopupWithMessage(ac.getLiteralsValueByKey("loading"));
							new AsyncLoadRaw().execute(evt.getProfileIndex(), HelperUtils.TEST);
						break;

					}
					break;
				}
			}
		} else if(evt.getData().equals(SmsPayment.MESSAGE_ERROR))
		{
			if(popupWindow != null)
				popupWindow.dismiss();
		}
		
	}

}
